/* John Zigler and John Spicher
 * Cryptography, Fall 2011
 * Final Project
 */

package cryptofinal;
import java.util.Stack;
public class CharacterNode {
    private char myChar;
    private Stack<CharacterNode> children;
    private boolean endOfWord;

    /* Constructor method
     * Accepts as parameter the character to be associated with this node.
     */
    public CharacterNode(char newChar){
        myChar=newChar;
        endOfWord=false;
        children = new Stack();
    }

    /* Add method
     * Accepts as parameter the word to add to the dictionary. Recursively
     * builds the tree so that navigating the tree could result in the given
     * tree.
     */
    public void add(String newWord){
        if (newWord.length()==0){
            endOfWord=true;
            return;
        }
        for (int i=0;i<children.size();i++){
            if (Character.toUpperCase(children.elementAt(i).myChar)
                    ==Character.toUpperCase(newWord.charAt(0))){
                children.elementAt(i).add(newWord.substring(1));
                return;
            }
        }
        CharacterNode newChild = new CharacterNode(newWord.charAt(0));
        children.add(newChild);
        newChild.add(newWord.substring(1));
    }

    /* Contains method
     * Accepts as paramters the string to look up. Recursively navigates the
     * tree to determine if the given string is in the dictionary. Ignores case.
     */
    public boolean contains(String thisWord){
        if (thisWord.length()==0) return endOfWord;
        for (int i=0;i<children.size();i++)
            if (Character.toUpperCase(children.elementAt(i).myChar)
                            ==Character.toUpperCase(thisWord.charAt(0)))
                return children.elementAt(i).contains(thisWord.substring(1));
        return false;
    }

    /* PrintAll method
     * Prints to the console all words that can be built by the tree.
     */
    public void printAll(){printAllStartingWith("");}

    /* PrintAllStartingWith method
     * Used recursively for printAll method. 
     */
    private void printAllStartingWith(String parentString){
        if (endOfWord) System.out.println(parentString+myChar);
        for (int i=0;i<children.size();i++)
            children.elementAt(i).printAllStartingWith(parentString+myChar);
    }
}
